import React, {useEffect, useState} from 'react';
import {
  View,
  Text,
  FlatList,
  TouchableOpacity,
  Image,
  StyleSheet,
  Clipboard,
} from 'react-native';
import useHideTabBar from '../utils/useHideTabBar';
import theme from '../utils/theme';
import API, {getUserId} from '../Network/Api';
import { normalize, screenHeight } from "../utils/commonUtils";
import {showToast} from '../utils/toastUtils';
import Toast from 'react-native-toast-message';
import { CustomText } from "../customview/CustomText";

const PointExchangeRecordPage = ({route, navigation}) => {
  const [orders, setOrders] = useState([]); // 存储订单数据
  const [refreshing, setRefreshing] = useState(false); // 下拉刷新状态
  const [page, setPage] = useState(1); // 当前页码
  const [hasMore, setHasMore] = useState(false); // 是否还有更多数据
  useHideTabBar(navigation);

  useEffect(() => {
    fetchOrders();
  }, []);

  const fetchOrders = async () => {
    try {
      const pageSize = '20';
      const response = await API.pointsExchangeRecordReq(page, 20);
      if (response.resultCode === '1') {
        const list = response.data.pointRecord.rows || [];
        const total = response.data.pointRecord.total;
        if (page === 1) {
          setOrders(list);
        } else {
          setOrders(prevRecords => [...prevRecords, ...list]);
        }
        setHasMore(orders.length + list.length < total);
      }
    } catch (error) {
      console.error('获取订单数据失败:', error);
      setHasMore(false);
    }
  };

  const onRefresh = () => {
    setRefreshing(true);
    setPage(1);
    fetchOrders();
    setRefreshing(false);
  };

  const onEndReached = () => {
    if (hasMore) {
      const nextPage = page + 1;
      setPage(nextPage);
      fetchOrders();
    }
  };

  const copyOrderId = orderId => {
    Clipboard.setString(orderId);
    showToast({text2: '单号复制成功！'});
  };

  const OrderItem = ({order}) => (
    <View style={styles.orderItem}>
      <View style={styles.orderHeader}>
        <CustomText style={styles.dateText}>时间：{order.updateTime}</CustomText>
        <CustomText style={styles.statusText}>未使用</CustomText>
      </View>
      <View style={styles.separator} />
      <View style={styles.productInfo}>
        <Image source={theme.app.productImg} style={styles.productImage} />
        <View style={styles.productDetails}>
          <CustomText style={styles.productName}>{order.spmc}</CustomText>
          <CustomText style={styles.price}>兑换积分：{order.spsxjf}</CustomText>
        </View>
      </View>
      <View style={styles.separator} />
      <TouchableOpacity style={styles.orderIdStyle} onPress={() => copyOrderId(order.id)}>
        <CustomText style={styles.orderIdText}>单号：{order.id}</CustomText>
      </TouchableOpacity>
    </View>
  );

  const EmptyListComponent = () => (
    <View style={styles.emptyListContainer}>
      <CustomText style={styles.emptyListText}>暂无兑换记录</CustomText>
    </View>
  );

  return (
    <View style={styles.container}>
      {/* 订单列表 */}
      <FlatList
        data={orders}
        renderItem={({item}) => <OrderItem order={item} />}
        keyExtractor={item => item.id}
        onRefresh={onRefresh}
        refreshing={refreshing}
        onEndReached={onEndReached}
        onEndReachedThreshold={0.1}
        ListEmptyComponent={EmptyListComponent}
      />
      <Toast />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f8f8f8',
  },
  orderItem: {
    backgroundColor: '#ffffff',
    marginTop: 10,
    borderRadius: 10,
    marginHorizontal: 10,
  },
  orderHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginHorizontal: 10,
    marginVertical: 10,
  },
  dateText: {
    fontSize: normalize(14),
    color: '#333',
  },
  statusText: {
    fontSize: normalize(14),
    color: '#F96C0D',
  },
  separator: {
    height: 1,
    backgroundColor: '#979797',
    opacity: 0.1,
  },
  productInfo: {
    flexDirection: 'row',
  },
  productImage: {
    width: 65,
    height: 65,
    marginRight: 10,
    marginTop: 25,
    marginLeft: 15,
    marginBottom: 12,
  },
  productDetails: {
    flex: 1,
    marginTop: 25,
  },
  productName: {
    fontSize: normalize(16),
    fontWeight: 'bold',
    color: '#333',
  },
  price: {
    fontSize: normalize(14),
    color: '#F96C0D',
    marginTop: 10,
  },
  emptyListContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: screenHeight / 3,
  },
  emptyListText: {
    flex: 1,
    fontSize: normalize(16),
    color: '#999',
  },
  orderIdStyle: {
    flexDirection: 'row-reverse',
    marginVertical: 10,
    marginRight: 10,
  },
  orderIdText: {
    fontSize: normalize(12),
    color: '#888',
  },
});

export default PointExchangeRecordPage;
